import { watch, ref } from 'vue'
import { isString } from '@/utils/is'
import { useI18n } from './useI18n'

export interface TitleOptions {
  appTitle?: string
}

export const useTitle = (newTitle?: string, options?: TitleOptions) => {
  const { t } = useI18n()
  const defaultAppTitle = options?.appTitle || 'EPMS Element'
  
  const title = ref(
    newTitle ? `${defaultAppTitle} - ${t(newTitle as string)}` : defaultAppTitle
  )

  watch(
    title,
    (n, o) => {
      if (isString(n) && n !== o && document) {
        document.title = n
      }
    },
    { immediate: true }
  )

  const setTitle = (newTitle: string, appTitle?: string) => {
    const baseTitle = appTitle || defaultAppTitle
    title.value = newTitle ? `${baseTitle} - ${t(newTitle)}` : baseTitle
  }

  return {
    title,
    setTitle
  }
}
